<template>
  <page-wrap
    ref="pageWrap"
    hideTab
    back
    bg-color="#fff"
    :showTop="showTop"
    :title="title"
    :dark="true"
    :hideSafeArea="true"
  >
    <view
      class="styleContainer"
      :style="{ backgroundImage: 'url(' + srcBg + ')' }"
    >
      <view
        class="positionNameContainer"
        :style="'padding-top:' + navHeight + 'px'"
      >
        <view class="positonName" @click="handlePositionNameClick"
          >{{ positionName }}
          <u-icon name="arrow-right" size="32"></u-icon>
          <!-- <img
            :src="careerSalaryReportRightArrow"
            class="careerSalaryReportRightArrow"
            alt=""
          /> -->
        </view>
        <view class="positionSwitcher" @click="handlePositionSwitch">
          <img :src="positionSwicher" alt="" /> 切换职业
        </view>
      </view>
      <view class="basicSalaryCard">
        <view class="basicMonthSalary">
          <text class="orange">
            ¥
            <text class="salaryNum">{{
              regionAvgSalaryInfo.salaryNum || '--'
            }}</text>
          </text>
          <text class="salaryLabel">平均月薪</text>
        </view>
      </view>
      <view
        :class="{ menu: true, showMenuBg: showMenuBg }"
        :style="'top:' + (navHeight - 2) + 'px'"
      >
        <u-tabs
          :current="currentIndex"
          name="title"
          :list="salaryTabList"
          @change="handleTabClick"
          height="60"
          :active-item-style="activeItemStyle"
          :gutter="40"
          :bar-style="barStyle"
          font-size="32"
          :inactive-color="'#999999'"
        ></u-tabs>
      </view>
      <view class="contentContainer">
        <template>
          <salaryAnalysis
            v-if="currentIndex == 0"
            :currentIndex="currentIndex"
            :title="'薪酬分析'"
            :positionId="positionId"
            :positionName="positionName"
            :personId="personId"
            @regionChange="regionChange"
            :showFilterBox="showFilterBox"
            :currentRegion="currentRegion"
            :hideCharts.sync="hideCharts"
          >
          </salaryAnalysis>
        </template>
        <template>
          <RecruitmentAnalysis
            v-if="currentIndex == 1"
            :currentIndex="currentIndex"
            :title="'招聘分析'"
            :positionId="positionId"
            :positionName="positionName"
            :personId="personId"
            :showFilterBox="showFilterBox"
          >
          </RecruitmentAnalysis>
        </template>
      </view>
      <view class="fixedButtons" v-if="fromSxh == 'fromSxh'">
        <view class="return-sxh-home" @click="returnSxhHome">返回首页</view>
      </view>
      <view class="fixedButtons" v-else>
        <image class="shareWithOthers" :src="shareWithOthers" />
        <!-- <image class="hat" :src="hat" /> -->
        <button
          :class="{ fixedButtonItem: true, disabled: false }"
          :open-type="openType"
          @click="shareHandleClick"
        >
          分享薪酬报告
        </button>
        <view
          :class="isShared ? 'fixedButtonItem' : 'disabled'"
          @click="sharePdf"
          >下载发送薪酬报告</view
        >
      </view>
    </view>
    <FilterBox
      ref="filterBox"
      :keywordFromParent="positionName"
      @update="handleFilter($event)"
      :showFilterBox.sync="showFilterBox"
    ></FilterBox>
    <LoginDialog
      ref="loginDialog"
      @loginSuccessBack="loginSuccessBack"
      @closeDialog="closeDialog"
    >
    </LoginDialog>
  </page-wrap>
</template>
<script>
import { getOneRegionAvgSalary } from '@/api/modules/positionDictionary';
import salaryAnalysis from './components/salaryAnalysis.vue';
import RecruitmentAnalysis from './components/RecruitmentAnalysis.vue';
import FilterBox from './components/filterBox.vue';
import ShareMixin from '@/mixins/share';
import LoginDialog from '@/components/LoginDialog';
import {
  addBuryingPoint,
  addPositionTopicPoint,
  getUserInfo,
  cardRegist,
  getPersonOrDefaultCardType,
  getCareerResearchReport,
  getPositionTemplate,
} from '@/api/modules/career';
export default {
  mixins: [ShareMixin],
  name: 'careerSalaryReport',
  components: {
    salaryAnalysis,
    RecruitmentAnalysis,
    FilterBox,
    LoginDialog,
  },
  data() {
    return {
      showMenuBg: false,
      hat: this.$imgBase + 'career/positionDictionary/hat.png',
      shareWithOthers:
        this.$imgBase + 'career/positionDictionary/sharePicture.png',
      openType: '',
      isShared: false, // 用作判断是否分享过解锁永久下载机会
      showFilterBox: false,
      shareTitle: '123',
      topTitle: '--',
      parentTitle: '--',
      positionId: '114177',
      personId: uni.getStorageSync('person-id').slice(2) || '',
      shareQuery: `jumpPersonId=${this.personId}&jumpSource=10&sourceType=10&positionId=${this.positionId}&positionName=${this.positionName}&regionId=${this.regionId}&regionName=${this.regionName}&parentTitle=${this.parentTitle}&topTitle=${this.topTitle}`,
      sharePath: `/pagesSub/careerNew/positionDictionary/careerSalaryReport/index?${this.shareQuery}`,
      regionAvgSalaryInfo: {},
      currentRegion: {},
      positionName: '--',
      title: '',
      showTop: false,
      // salaryTabList: [{ name: "薪酬分析" }, { name: "招聘分析" }],
      salaryTabList: [{ name: '薪酬分析' }],
      currentIndex: '',
      activeItemStyle: {
        'font-weight': '600',
        color: '#000000',
        'font-size': '32rpx',
      },
      barStyle: {
        width: '20px',
        height: '8px',
        background:
          'linear-gradient(270deg, rgba(255, 255, 255, 0) 0%, #F75A3E 100%)',
        'border-radius': '4px',
        left: '0',
        bottom: '0rpx',
      },
      navHeight: getApp().globalData.navHeight,
      rightArrow: this.$imgBase + 'career/right-arrow.png',
      positionSwicher:
        this.$imgBase + 'career/positionDictionary/positionSwicher.png',
      careerSalaryReportRightArrow:
        this.$imgBase +
        'career/positionDictionary/careerSalaryReportRightArrow.png',
      srcBg:
        this.$imgBaseSelf + 'career/positionDictionary/career_search_bg.png',
      shareCareerInfoParams: {},
      hideCharts: false,
      buryingPointId: '',
      cardType: '',
      tempParams: {}, // 用于分享出去再点回来的参数
      fromSxh: '',
    };
  },
  created() {},
  onShow() {
    //  埋点统计访问次数
    this.addBuryingPointFn(20096, '', '', '', '');
    wx.reportEvent('salary_detail_enter_click', {}); //薪酬详情—进入薪酬详情页
    if (getApp().globalData.sharedPositionIdList.includes(this.positionId)) {
      this.isShared = true;
    } else {
      this.isShared = false;
    }
    if (this.personId) {
      this.openType = 'share';
    } else {
      this.openType = '';
    }
  },
  onLoad(opt) {
    console.log('----opt------->', opt);
    this.fromSxh = opt.fromSxh;
    this.tempParams = opt;
    this.shareTitle = `我正在看${this.positionName}薪酬报告`;
    //一定一定要注意onload的时候才会获取到参数，但是组件会在这之前初始化，导致组件没有获取到regionId!
    let {
      positionId,
      positionName,
      regionId,
      regionName,
      topTitle,
      parentTitle,
    } = opt;
    if (positionName && this.containsUrlEncodedChinese(positionName)) {
      positionName = this.decodeUrlString(positionName);
      // console.log("positionName被decode了", positionName);
    }
    if (topTitle && this.containsUrlEncodedChinese(topTitle)) {
      topTitle = this.decodeUrlString(topTitle);
    }
    if (parentTitle && this.containsUrlEncodedChinese(parentTitle)) {
      parentTitle = this.decodeUrlString(parentTitle);
    }
    if (regionName && this.containsUrlEncodedChinese(regionName)) {
      regionName = this.decodeUrlString(regionName);
    }
    this.currentRegion.value = regionId;
    this.currentRegion.label = regionName;
    this.positionName = positionName;
    this.topTitle = topTitle;
    this.parentTitle = parentTitle;
    this.positionId = positionId;
    const params = `positionId=${this.positionId}&positionName=${this.positionName}&regionId=${this.currentRegion.value}&regionName=${this.currentRegion.label}&parentTitle=${this.parentTitle}&topTitle=${this.topTitle}`;
    this.sharePath =
      '/pagesSub/careerNew/positionDictionary/careerSalaryReport/index?' +
      params;
    this.reqGetOneRegionAvgSalary();
    let jumpPersonId = '';
    if (opt.jumpPersonId) {
      jumpPersonId = opt.jumpPersonId;
    }
    let jumpSource = '';
    if (opt.jumpSource) {
      jumpSource = opt.jumpSource;
    }
    let sourceType = '';
    if (opt.sourceType) {
      sourceType = opt.sourceType;
    }

    this.shareCareerInfoParams = {
      etId: 20048,
      id: this.buryingPointId ? this.buryingPointId : '', //后台要求不能传空，未登录也要统计
      personId: uni.getStorageSync('person-id').slice(2) || '0',
      cardType: this.cardType
        ? this.cardType
        : uni.getStorageSync('cardType') || this.cardType,
      consultantId: uni.getStorageSync('sellId')
        ? uni.getStorageSync('sellId')
        : '',
      originType: this.originFrom == 'shareLink' ? 10 : 20,
      statType: '40',
      jumpPersonId: jumpPersonId,
      jumpSource: jumpSource,
      sourceType: sourceType,
    };
    //外部链接点击统计事件
    if (jumpSource && sourceType) {
      this.addBuryingPointFn(20082, '50', jumpPersonId, jumpSource, sourceType);
    }
    setTimeout(() => {
      this.currentIndex = 0;
    }, 300);
  },
  mounted() {
    if (!this.personId) {
      this.showLoginDialog();
    }
  },
  onPageScroll(res) {
    // console.log("res.scrollTop", res.scrollTop);

    this.showTop = res.scrollTop > 40;
    this.title = this.showTop ? this.positionName : '';
    this.showMenuBg = res.scrollTop > 150;
  },
  // onShareAppMessage(res) {
  //   this.shareHandleClick();
  //   return {
  //     title: `我正在看${this.positionName}薪酬报告`,
  //     path: `/pagesSub/careerNew/positionDictionary/careerSalaryReport/index${this.tempParams}`,
  //     // imageUrl: "/static/imgs/mylogo.png",
  //   };
  // },
  // 自定义页面的分享到朋友圈
  // onShareTimeline(res) {
  //   this.shareHandleClick();
  //   return {
  //     title: `我正在看${this.positionName}薪酬报告`,
  //     path: `/pagesSub/careerNew/positionDictionary/careerSalaryReport/index${this.tempParams}`,
  //     // imageUrl: "/static/imgs/mylogo.png",
  //   };
  // },
  watch: {
    positionId: {
      handler(newValue, oldValue) {
        if (oldValue == String(newValue)) {
          return;
        }
        this.shareTitle = `我正在看${this.positionName}薪酬报告`;
        if (
          getApp().globalData.sharedPositionIdList.includes(this.positionId)
        ) {
          this.isShared = true;
        } else {
          console.log('这里进入了false侦听器');
          this.isShared = false;
        }
      },
      immediate: true,
    },
  },
  methods: {
    returnSxhHome() {
      uni.reLaunch({ url: '/pagesSub/doubleChannelChoosingMeeting/index' });
    },
    shareHandleClick() {
      console.log('这里发生了点击分享事件', this.personId);
      if (!this.personId) {
        this.showLoginDialog();
      } else {
        let tempSharedPositionIdList = [];
        tempSharedPositionIdList = getApp().globalData.sharedPositionIdList;
        tempSharedPositionIdList.push(this.positionId);
        tempSharedPositionIdList = Array.from(
          new Set(tempSharedPositionIdList)
        ); // 去重
        getApp().globalData.sharedPositionIdList = tempSharedPositionIdList; // 之后判断isShared就来便利数组 来判断此份报告是否有被分享过
      }
    },
    async getCareerResearchReportFn() {
      const params = {
        reportType: 'salary_report',
        ylPositionId: this.positionId,
      };
      const reportRes = await getCareerResearchReport(params);
      if (reportRes.code == 200) {
        console.log('reportRes', reportRes);
        wx.downloadFile({
          url: reportRes.data.pdfUrl,
          success(res) {
            // Repost after download
            console.log('res', res);
            wx.shareFileMessage({
              filePath: res.tempFilePath,
              fileName: reportRes.data.reportName + '.pdf',
              success() {},
              fail() {
                uni.showToast({
                  icon: 'none',
                  title: '分享失败',
                  duration: 2000,
                });
              },
            });
          },
          fail() {
            uni.showToast({
              icon: 'none',
              title: '该职业暂无薪酬报告~',
              duration: 2000,
            });
          },
        });
      }
    },
    sharePdf() {
      if (!this.personId) {
        this.showLoginDialog();
      } else {
        if (this.isShared) {
          this.getCareerResearchReportFn();
        } else {
          console.log('this.isShared', this.isShared);
          return;
        }
      }
    },
    showLoginDialog() {
      this.hideCharts = true;
      this.$refs.loginDialog.setVisibility(true);
    },
    async cardRegistFn() {
      const params = {
        cardKey: this.cardKey || '1', // cardType或者cardKe至少传一个
        cardType: this.cardType
          ? this.cardType
          : uni.getStorageSync('cardType') || this.cardType,
        sellId: +this.consultantId,
      };
      const res = await cardRegist(params);
      if (res.code != 200) {
        uni.showToast({ icon: 'none', title: res.status_desc, duration: 1500 });
      }
    },
    async getUserInfoFn() {
      const params = { uid: '' };
      const res = await getUserInfo(params);
      if (res.code == 200) {
        // cardNoe和cardType是同时存在的
        await this.getPersonOrDefaultCardTypeFn();
        if (!res.data.cardNo) {
          // 说明此时没有绑卡 要自动绑卡(这里是针对中学生的项目)
          await this.cardRegistFn();
        }
      }
    },
    async getPersonOrDefaultCardTypeFn() {
      const params = {
        personId: uni.getStorageSync('person-id').slice(2) || undefined,
        cardSource: 'HIGH_ASSESSMENT', // 如果是默认注册是关于高考的卡，就要穿这个参数获取到cardType
      };
      const res = await getPersonOrDefaultCardType(params);
      if (res.code == 200 && res.data.cardType) {
        this.cardType = res.data.cardType;
        uni.setStorageSync('cardType', res.data.cardType);
      }
    },
    //普通的埋点+事件停留埋点
    async addBuryingPointFn(
      etId,
      statType,
      jumpPersonId,
      jumpSource,
      sourceType
    ) {
      const params = {
        etId: etId,
        id: this.buryingPointId ? this.buryingPointId : '', //后台要求不能传空，未登录也要统计
        personId: uni.getStorageSync('person-id').slice(2) || '0',
        cardType: this.cardType
          ? this.cardType
          : uni.getStorageSync('cardType') || this.cardType,
        consultantId: uni.getStorageSync('sellId')
          ? uni.getStorageSync('sellId')
          : '',
        originType: this.originFrom == 'shareLink' ? 10 : 20,
        statType: statType ? statType : '10',
        jumpPersonId: jumpPersonId,
        jumpSource: jumpSource,
        sourceType: sourceType,
      };
      const res = await addBuryingPoint(params);
    },
    async addPositionTopicPointFn(eventType, dataId) {
      const params = {
        eventType: eventType,
        dataId: dataId,
        personId: uni.getStorageSync('person-id').slice(2) || '0',
        description: '中学生高考点击了职业',
        platform: '1',
      };
      const res = await addPositionTopicPoint(params);
    },
    async loginSuccessBack() {
      this.personId = uni.getStorageSync('person-id').slice(2) || undefined;
      wx.reportEvent('salary_detail_login_consultant_click', {}); //薪酬详情—手机号一键登录
      await this.getUserInfoFn();
      this.openType = 'share';
    },
    closeDialog() {
      this.hideCharts = false;
    },
    containsUrlEncodedChinese(str) {
      // 正则表达式：匹配 % 后面跟着两个十六进制数字的模式
      const urlEncodedChinesePattern = /%[A-Fa-f0-9]{2}/;
      return urlEncodedChinesePattern.test(str);
    },
    decodeUrlString(encodedStr) {
      try {
        return decodeURIComponent(encodedStr);
      } catch (e) {
        console.error('Error decoding URL string:', e);
        return encodedStr; // 如果解码失败，返回原始字符串
      }
    },
    async handlePositionNameClick() {
      let params = `positionName=${this.positionName}&positionId=${this.positionId}&parentTitle=${this.parentTitle}&topTitle=${this.topTitle}`;
      this.addPositionTopicPointFn(2, this.positionId);
      //请求接口看是否走新页面
      const templateId = await this.getPositionTemplateFn(this.positionId);
      if (templateId == 6) {
        uni.navigateTo({
          url: `/pagesSub/careerNewPositionDictionary/positionDetail?${params}`,
        });
      } else {
        uni.navigateTo({
          url: `/pagesSub/careerNew/positionDictionary/positionDetail?${params}`,
        });
      }
      // uni.navigateTo({
      //   url: `/pagesSub/careerNew/positionDictionary/positionDetail?${params}`,
      // });
    },
    async getPositionTemplateFn(positionId) {
      const res = await getPositionTemplate({ positionId: positionId });
      if (res.code == 200) {
        return res.data.templateId;
      } else {
        return 0;
      }
    },
    freshData() {
      const params = `positionId=${this.positionId}&positionName=${this.positionName}&regionId=${this.currentRegion.value}&regionName=${this.currentRegion.label}&parentTitle=${this.parentTitle}&topTitle=${this.topTitle}`;
      this.sharePath =
        '/pagesSub/careerNew/positionDictionary/careerSalaryReport/index?' +
        params;
      this.reqGetOneRegionAvgSalary();
    },
    handlePositionSwitch() {
      this.showFilterBox = true;
      this.$nextTick(() => {
        this.$refs.filterBox.init();
      });
    },
    //切换职业之后触发的方法
    handleFilter(data) {
      console.log('切换职业之后触发的方法');

      this.showFilterBox = false;
      this.positionName = data.tagTitle;
      this.positionId = data.positionId;
      this.freshData();
    },
    handleShareClick() {
      wx.showShareMenu({
        withShareTicket: true, // 是否使用带 shareTicket 的转发详情
        menus: ['shareAppMessage', 'shareTimeline'], // 可以自定义要显示的分享菜单项
      });
    },
    reqGetOneRegionAvgSalary() {
      const params = {
        id: this.positionId,
        regionIds: this.currentRegion.value || '',
      };
      getOneRegionAvgSalary(params)
        .then((res) => {
          if (res.code == 200) {
            this.regionAvgSalaryInfo = res.data;
          }
        })
        .catch((e) => {
          console.log(e);
        });
    },
    handleTabClick(index) {
      this.currentIndex = index;
      this.positionId = new Number(this.positionId);
      uni.pageScrollTo({
        scrollTop: 151, // 滚动到页面顶部
        duration: 300, // 可选，滚动动画的时长，单位为毫秒
      });
    },
    //切换城市
    regionChange(region) {
      console.log('切换城市之后触发的方法');
      this.currentRegion = region;
      this.freshData();
    },
  },
};
</script>
<style lang="scss" scoped>
@font-face {
  font-family: 'D-DIN-PRO-700-Bold';
  /*定义字体名称*/
  src: url('https://img3.job1001.com/ypMp/elan/images/career/positionDictionary/D-DIN-PRO-700-Bold.ttf');
}

.styleContainer {
  background-image: url($img-base + 'career/positionDictionary/bg_major_searchhome.webp');
  background-size: 100% 100%;
  // height: 100vh;
  // padding: 0 16rpx;
  & > view {
    margin: 0 16rpx;
  }
  .positionNameContainer {
    // width: 100%;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 36rpx 16rpx 0rpx;
    margin-bottom: 32rpx;

    .positonName {
      display: inline;
      align-items: center;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      font-size: 48rpx;
      color: #000000;
      line-height: 66rpx;
      text-align: left;
      font-style: normal;
      ::v-deep .u-icon__icon {
        margin-left: 8rpx;
        top: -4rpx !important;
      }

      .careerSalaryReportRightArrow {
        width: 32rpx;
        height: 32rpx;
        margin-left: 18rpx;
      }
    }

    .positionSwitcher {
      display: flex;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 28rpx;
      color: #199ab0;
      line-height: 40rpx;
      text-align: left;
      font-style: normal;
      min-width: 200rpx;
      margin-left: 20rpx;
      padding-left: 40rpx;
      img {
        width: 32rpx;
        height: 32rpx;
        margin-right: 16rpx;
      }
    }
  }

  .basicSalaryCard {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 686rpx;
    height: 128rpx;
    background: rgba(255, 255, 255, 0.6);
    box-shadow: 0rpx 4rpx 20rpx 0rpx #d1eaf1;
    border-radius: 20rpx;
    backdrop-filter: blur(12px);
    padding: 0rpx 32rpx;
    font-size: 36rpx;
    margin: 0 auto;

    .basicMonthSalary {
      display: flex;
      align-items: center;

      .orange {
        color: #f75a3e;
        font-family: D-DIN-PRO-700-Bold;
      }

      .salaryNum {
        font-size: 56rpx;
      }

      .salaryLabel {
        display: inline-block;
        font-family: PingFangSC, PingFang SC;
        font-weight: 400;
        font-size: 30rpx;
        color: #888888;
        line-height: 42rpx;
        text-align: left;
        font-style: normal;
        margin-left: 14rpx;
        margin-top: 8rpx;
      }
    }

    .basicSalaryCitySelector {
      background: #eef4f6;
      border-radius: 12rpx;
      padding: 16rpx 14rpx;
      font-family: PingFangSC, PingFang SC;
      font-weight: 400;
      font-size: 24rpx;
      color: #888888;
      line-height: 24rpx;
      text-align: left;
      font-style: normal;

      .rightDown {
        margin-bottom: 6rpx;
      }
    }
  }

  .menu {
    margin-top: 54rpx;
    position: sticky;
    left: 0rpx;
    &.showMenuBg {
      width: 100vw;
      background-color: white;
      z-index: 2000;

      // border-radius: 0 0 24rpx 24rpx;
      margin: 0;
      left: -16rpx;
      padding: 0 16rpx 12rpx;
    }
  }

  .contentContainer {
    margin-top: 30rpx;
    padding-bottom: calc(30rpx + constant(safe-area-inset-bottom));
    padding-bottom: calc(30rpx + env(safe-area-inset-bottom));
  }

  .fixedButtons {
    z-index: 999;
    // width: calc(100vw - 64rpx);
    position: fixed;
    display: flex;
    justify-content: space-between;
    bottom: 80rpx;
    width: 100vw;
    margin: 0 auto;
    flex-direction: row;
    align-items: center;
    justify-content: center;
    .return-sxh-home {
      width: 680rpx;
      height: 96rpx;
      background: #ff711e;
      border-radius: 200rpx;
      color: #ffffff;
      font-family: PingFang-SC, PingFang-SC;
      font-weight: bold;
      font-size: 32rpx;
      color: #ffffff;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
    }
    .fixedButtonItem {
      background-color: #ff711e;
      color: white;
      font-size: 36rpx;
      padding: 40rpx 50rpx;
      border-radius: 12rpx;
      height: 90rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
    }
    .disabled {
      background-color: #ffc8a8;
      color: white;
      font-size: 36rpx;
      padding: 40rpx 50rpx;
      border-radius: 12rpx;
      height: 90rpx;
      display: flex;
      flex-direction: row;
      align-items: center;
    }
    .shareWithOthers {
      width: 258rpx;
      height: 34rpx;
      position: fixed;
      bottom: 170rpx;
      left: 50rpx;
    }
    .hat {
      width: 24rpx;
      height: 24rpx;
      position: fixed;
      bottom: 176rpx;
      left: 60rpx;
      // z-index: 1000;
    }
  }
}

::v-deep .u-tabs {
  background: transparent !important;
}
</style>
